<template>
    <div>
        <Form :label-width="80" inline>
            <FormItem label="字段名称">
                <Input @on-clear="getAllCode" v-model="map.codeName" clearable class="myform"/>
            </FormItem>
            <FormItem label="字段类型">
                <Select @on-clear="getAllCode" v-model="map.codeType" clearable class="myform">
                    <Option v-for="item in codeTypeList" :key="item" :value="item">{{item}}</Option>
                </Select>
                <Button icon="ios-search" type="success" @click="getAllCode" class="btn">查询</Button>
                <Button class="btn" icon="md-add-circle" @click="addFlag = true" type="info">添加</Button>
            </FormItem>
        </Form>
        <Table :loading="loading" border :columns="columns" :data="codeData">
            <template slot-scope="{ row, index }" slot="action">
                <div v-if="!row.editFlag">
                    <Button type="primary" icon="ios-build" size="small" style="margin-right: 5px"
                            @click="row.editFlag = true">编辑
                    </Button>
                    <Poptip
                            confirm
                            transfer
                            title="是否删除?"
                            @on-ok="remove(row,index)"
                            @on-cancel="$Message.info('已取消')">
                        <Button type="error" icon="md-trash" size="small">删除</Button>
                    </Poptip>
                </div>
                <div v-else>
                    <Button type="success" icon="ios-paper" size="small" style="margin-right: 5px"
                            @click="row.editFlag = false,saveUpdateCode(row)">保存
                    </Button>
                    <Button type="info" icon="ios-hand" size="small" @click="cancelSave(row,index)">取消</Button>
                </div>
            </template>
        </Table>
        <br/>
        <Page :total="total" :page-size="map.size" @on-change="changePage" @on-page-size-change="changePageSize"
              show-sizer show-total show-elevator />
        <Modal v-model="addFlag"
               title="字段添加">
            <Form :model="codeDo" ref="codeDo" :rules="ruleValidate" :label-width="80">
                <FormItem prop="codeType" label="字段类型">
                    <Select v-model="codeDo.codeType" style="width: 300px" v-if="!cutover" clearable
                            @on-select="(e)=>{this.cutover = e.value =='true'?true:false}">
                        <Option v-for="item in codeTypeList" :key="item" :value="item">{{item}}</Option>
                        <Option value=true>其他</Option>
                    </Select>
                    <Input v-if="cutover" v-model="codeDo.codeType" style="width: 300px"/>
                    <Button v-if="cutover" @click="cutover=!cutover" style="margin-left: 15px">返回下拉</Button>
                </FormItem>
                <FormItem prop="codeName" label="字段名称">
                    <Input style="width: 300px" clearable v-model="codeDo.codeName" clearable/>
                </FormItem>
                <transition name="bounce">
                    <FormItem prop="codeTheCode" v-if="codeDo.codeType == 'userGroup'" label="代码名称">
                        <Select style="width: 300px" clearable v-model="codeDo.codeTheCode">
                            <Option value="admin">admin</Option>
                            <Option value="teacher">teacher</Option>
                            <Option value="student">student</Option>
                        </Select>
                    </FormItem>
                </transition>
            </Form>
            <Button slot="footer" type="primary" long @click="saveAddCode">确认添加</Button>
        </Modal>
    </div>
</template>

<script>
    import {AddCodeRuleValidate} from "@c/ruleValidate";

    export default {
        data() {
            return {
                loading: false,
                ruleValidate: AddCodeRuleValidate(),
                total: 0,
                map: {
                    page: 1,
                    size: 10,
                    codeName: null,
                    codeType: null,
                },
                cutover: false,
                addFlag: false,
                codeDo: {
                    codeType: null,
                    codeName: null,
                    codeTheCode: null,
                    foreignKey: 0
                },
                codeTypeList: [],
                columns: [
                    {
                        type: 'index',
                        width: 70,
                        title: '序号',
                        align: 'center'
                    },
                    {
                        title: '字段名称',
                        sortable: true,
                        render: (h, params) => {
                            if (params.row.editFlag) {
                                return <i-input value={params.row.codeName} oninput={(e) => {
                                    params.row.codeName = e
                                }}/>
                            } else {
                                return <span>{params.row.codeName}</span>
                            }
                        }
                    },
                    {
                        title: '字段类型',
                        sortable: true,
                        render: (h, params) => {
                            return <div><span>{params.row.codeType}</span>
                                <span v-show={params.row.codeTheCode!=null }>【{params.row.codeTheCode}】</span></div>
                        }
                    }, {
                        title: "外键id",
                        sortable: true,
                        render: (h, params) => {
                            if (params.row.editFlag) {
                                return <i-input type="number" value={params.row.foreignKey} oninput={(e) => {
                                    params.row.foreignKey = e
                                }}/>
                            } else {
                                return <span>{params.row.foreignKey}</span>
                            }
                        }
                    }, {
                        title: "创建时间",
                        sortable: true,
                        key: "createTime"
                    },
                    {
                        title: "修改时间",
                        sortable: true,
                        key: "updateTime"
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 200,
                        align: 'center'
                    }
                ],
                codeData: [],
                assignCodeData: [] //克隆对象，作用：当用户点击编辑时候，修改了数据，但是却没保存，而是点击了取消，此对象用于恢复最初的数据
            }
        },
        methods: {
            /**
             * 点击下一页
             * @param val
             */
            changePage(val) {
                this.map.page = val
                this.getAllCode()
            },
            /**
             * 切换分页的每页显示条数
             * @param val
             */
            changePageSize(val) {
                this.map.size = val
                if (this.map.page === 1) {
                    this.getAllCode()
                }
            },
            /**
             * 获取全部的数据
             */
            getAllCode() {
                this.loading = true
                this.http.post("/code/getAllCode", this.qs.parse(this.map)).then(res => {
                    if (res.data) {
                        this.codeData = res.data.list.map(m => {
                            m.editFlag = false
                            return m
                        })
                        this.total = res.data.total
                        Object.assign(this.assignCodeData, this.codeData)
                    }
                }).finally(f => {
                    this.loading = false
                })
            },
            /**
             * 获取全部的类型
             */
            getAllCodeType() {
                this.http.get("/code/getAllCodeType").then(res => {
                    if (res.data) {
                        this.codeTypeList = res.data
                        if (!this.codeTypeList.includes("userGroup")) {
                            this.codeTypeList.push("userGroup")
                        }
                    }
                })
            },
            /**
             * 保存更新
             * @param row
             */
            saveUpdateCode(row) {
                let codeDO = row;
                this.http.put("/code/saveUpdateCode", this.qs.parse(codeDO)).then(res => {
                    if (res) {
                        this.$Message.success("修改成功")
                    }
                })
            },
            /**
             * 对象克隆
             */
            cancelSave(row,index) {
                Object.assign(row, this.assignCodeData[index])
            },
            /**
             * 删除数据
             * @param row
             * @param index
             */
            remove(row, index) {
                this.http.delete(`/code/removeCodeById/${row.codeId}`).then(res => {
                    if (res.data) {
                        this.$Message.success("删除成功")
                        this.codeData.splice(index, 1)
                    } else {
                        this.$Message.error("删除失败")
                    }
                })
            },
            /**
             * 保存添加
             */
            saveAddCode() {
                this.$refs['codeDo'].validate((val) => {
                    if (val) {
                        this.http.post("/code/saveAddCode", this.qs.parse(this.codeDo)).then(res => {
                            if (res.data) {
                                this.addFlag = false
                                this.$Message.success("添加成功")
                                this.getAllCode()
                                this.getAllCodeType()
                            }
                        })
                    } else {
                        this.$Message.error("不能为空")
                    }
                })
            }
        },
        created() {
            this.getAllCode()
            this.getAllCodeType()
        },
    }
</script>

<style scoped>
    .myform {
        width: 300px;
    }

    .btn {
        margin-left: 10px;
    }
</style>
